% Moorings QAQC code assignment GUI and associated event handlers
%
% Author: David Goldsmith, Wash. State Dept. of Ecology, dgol461@ecy.wa.gov
% Release date: < 9/15/2011

function varargout = QAQC_GUI_dev(varargin)
%QAQC_GUI_DEV M-file for QAQC_GUI_dev.fig
%      QAQC_GUI_DEV, by itself, creates a new QAQC_GUI_DEV or raises the existing
%      singleton*.
%
%      H = QAQC_GUI_DEV returns the handle to a new QAQC_GUI_DEV or the handle to
%      the existing singleton*.
%
%      QAQC_GUI_DEV('Property','Value',...) creates a new QAQC_GUI_DEV using the
%      given property value pairs. Unrecognized properties are passed via
%      varargin to QAQC_GUI_dev_OpeningFcn.  This calling syntax produces a
%      warning when there is an existing singleton*.
%
%      QAQC_GUI_DEV('CALLBACK') and QAQC_GUI_DEV('CALLBACK',hObject,...) call the
%      local function named CALLBACK in QAQC_GUI_DEV.M with the given input
%      arguments.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help QAQC_GUI_dev

% Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
                       'gui_Singleton',  gui_Singleton, ...
                       'gui_OpeningFcn', @QAQC_GUI_dev_OpeningFcn, ...
                       'gui_OutputFcn',  @QAQC_GUI_dev_OutputFcn, ...
                       'gui_LayoutFcn',  @QAQC_GUI_dev_LayoutFcn, ...
                       'gui_Callback',   []);
    if nargin && ischar(varargin{1})
        gui_State.gui_Callback = str2func(varargin{1});
    end

    if nargout
        [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
    else
        gui_mainfcn(gui_State, varargin{:});
    end
% End initialization code - DO NOT EDIT
end

% --- Executes just before QAQC_GUI_dev is made visible.
function QAQC_GUI_dev_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

    % Choose default command line output for QAQC_GUI_dev
    handles.output = hObject;

    % Update handles structure
    guidata(hObject, handles);

    % UIWAIT makes QAQC_GUI_dev wait for user response (see UIRESUME)
    % uiwait(handles.figure1);
end

% --- Outputs from this function are returned to the command line.
function varargout = QAQC_GUI_dev_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

    % Get default command line output from handles structure
    varargout{1} = handles.output;
end

function ActionsCallback(hObject,event,guiobject,h)
    global fig conn RVIDs extantQAcodes

  % Get the QA plots and _all_ the RVIDs of their plotted points
    qaPlots = findall(fig.fh, 'Tag', 'QAplot');
    refplot = findobj(qaPlots, 'UserData', 'T'); % Use temperature as the least likely to be absent
    allRVIDs= get(refplot, 'ZData'); RVIDs = allRVIDs(:,1);
    n       = length(RVIDs)/3; RVIDs = RVIDs(1:n);
  % If this is neither an Undo nor a Commit
    if ~ischar(h)
      % Get the new codes from the GUI ...        
        indices = cell2mat(get(findobj(h,'Style','popupmenu'),'Value'));
        indices = reshape(indices, 3, length(indices)/3);
        tmp = get(h, 'UserData');
        newVals = tmp{3}(indices(3,:));
        newFlgs = tmp{2}(indices(2,:));
        newCtLs = tmp{1}(indices(1,:));
      % ... and the brushed RVIDs
        mask    = fig.brushedQA.T.mask(1:n,1);
        RVIDs   = RVIDs(~isnan(mask));
    end
  % Now, loop over the plots
    for qaplot = qaPlots'
      % Gather parameter-dependent parts of the update query
        type = get(qaplot, 'UserData');
        switch type
            case 'P'
                i = 5;
                prefix = 'Pres';
            case 'T'
                i = 4;
                prefix = 'Temp';
            case 'S'
                i = 3;
                prefix = 'Sal';
            case 'O'
                i = 2;
                prefix = 'DO_Calc';
        end
        if i-2
            table = 'RawValue';
        else
            table = 'CalculatedValue';
        end
        if ischar(h) && strcmp(h, 'Commit')
            [val, flg, cl] = GetCodes(table, prefix);
            switch prefix
                case 'Pres'
                    extantQAcodes{2} = [val; flg; cl]';
                case 'Temp'
                    extantQAcodes{3} = [val; flg; cl]';
                case 'Sal'
                    extantQAcodes{4} = [val; flg; cl]';
                case 'DO_Calc'
                    extantQAcodes{5} = [val; flg; cl]';
            end
        else
            if ischar(h) % Undo case
              % Remember: values for undo are in extantQAcodes
                undo = qaplot;
                vals = extantQAcodes(7-i);
                mask = RVIDs;
            else
                undo = false;
                vals = {newVals(i), newFlgs(i), newCtLs(i)};
            end
          % Push the codes
            PushCodes(table, prefix, vals, undo);
          % Get them back
            [newV, newF, newC] = GetCodes(table, prefix);
          % Reset QAQC codes in qaplot
            ViewCodes(qaplot, ~isnan(mask), {newV, newF, newC}, n);
        end
    end
    
    function [val, flg, ctl] = assignNew(i)
        val = newVals(i);
        flg = newFlgs(i);
        ctl = newCtLs(i);
    end
end

function PushCodes(table, prefix, vals, undo)
    global conn RVIDs
    try
        if undo
            oldCodes  = vals{:};
            newCodes  = get(undo, 'CData');
            newCodes  = reshape(newCodes(:,1), length(RVIDs), 3);
          % Way I know works
            vals2push = [];
            whereCA   = {};
          % "Vectorized" way; Note: wasn't faster, but Steve B. might know a way to formulate the 
          % query so it's faster.
%             setQtemplate = ' UNION SELECT ''%d'' WHERE RawValueID=''%d''';
%             Q = {[prefix 'DataQualVal=(SELECT ''%d'' WHERE RawValueID=''%d'' '],...
%                  [prefix 'DataQualFlag=(SELECT ''%d'' WHERE RawValueID=''%d'' '],...
%                  [prefix 'DataQualCtrlLev=(SELECT ''%d'' WHERE RawValueID=''%d'' ']};
%             firsttimethru = true;
            for i=1:length(oldCodes(:,1))
              % Do old codes = new codes?
                if ~isequalwithequalnans(oldCodes(i,:), newCodes(i,:))
                  % Way I know works
                    vals2push(end+1,1:3) = oldCodes(i,:);
                    whereCA{end+1}   = ['where RawValueID = ''' num2str(RVIDs(i)) ''''];
                  % "Vectorized" way
%                     if firsttimethru
%                         Q{1} = sprintf(Q{1}, [oldCodes(i,1) RVIDs(i)]);
%                         Q{2} = sprintf(Q{2}, [oldCodes(i,2) RVIDs(i)]);
%                         Q{3} = sprintf(Q{3}, [oldCodes(i,3) RVIDs(i)]);
%                         firsttimethru = false;
%                     else
%                         Q{1} = [Q{1} sprintf(setQtemplate, [oldCodes(i,1) RVIDs(i)])];
%                         Q{2} = [Q{2} sprintf(setQtemplate, [oldCodes(i,2) RVIDs(i)])];
%                         Q{3} = [Q{3} sprintf(setQtemplate, [oldCodes(i,3) RVIDs(i)])];
%                     end
                end
            end
          % Way I know works
             try
                 update(conn, table, {[prefix 'DataQualVal'], [prefix 'DataQualFlag'], [prefix 'DataQualCtrlLev']}, ...
                              vals2push, whereCA);
             catch ME
                 try
                     oldupdate(conn, table, {[prefix 'DataQualVal'], [prefix 'DataQualFlag'], [prefix 'DataQualCtrlLev']}, ...
                                     vals2push, whereCA);
                 catch ME
                     uiwait(errordlg({'Oooops!  The required update query failed!  Here''s the returned error message: ', ...
                                      getReport(ME, 'extended', 'hyperlinks', 'off')}, 'Database Communication Error!'));
                     return
                 end
             end
          % "Vectorized" way; Note: wasn't faster, but Steve B. might know a way to formulate the 
          % query so it's faster.
%             exec(conn, ['UPDATE ' table ' SET ' strrep(Q{1}, '''NaN''', 'NULL') ')']);% ...
%             exec(conn, ['UPDATE ' table ' SET ' strrep(Q{2}, '''NaN''', 'NULL') ')']);% ...
%             exec(conn, ['UPDATE ' table ' SET ' strrep(Q{3}, '''NaN''', 'NULL') ')']);% ...
        else
            try
                update(conn, table, {[prefix 'DataQualVal'], [prefix 'DataQualFlag'], [prefix 'DataQualCtrlLev']}, ...
                             vals, where());
            catch ME
                try
                    oldupdate(conn, table, {[prefix 'DataQualVal'], [prefix 'DataQualFlag'], [prefix 'DataQualCtrlLev']}, ...
                                    vals, where());
                catch ME
                    uiwait(errordlg({'Oooops!  The required update query failed!  Here''s the returned error message: ', ...
                                     getReport(ME, 'extended', 'hyperlinks', 'off')}, 'Database Communication Error!'));
                    return
                end
            end
        end
    catch ME
        uiwait(errordlg({'Oooops!  The required update query failed!  Here''s the returned error message: ', ...
                         getReport(ME, 'extended', 'hyperlinks', 'off')}, 'Database Communication Error!'));
        return
    end
end

function [v, f, c] = GetCodes(table, prefix)
    global conn
    query = ['SELECT' ' ' prefix 'DataQualVal,' ...
                      ' ' prefix 'DataQualFlag,' ...
                      ' ' prefix 'DataQualCtrlLev' ' ' ...
             'FROM' ' ' table ' ' where()];
    curs = fetch(exec(conn, query));
    if ~isempty(curs.Message)
        throw(MException('CustomException:pushed_codes_query', curs.Message));
    end
    outdat = curs.Data;
    if strcmp(outdat{1}, 'No Data')
        throw(MException('CustomException:pushed_codes_query', outdat{1}));
    else
        try
            v = [outdat{:,1}];
            f = [outdat{:,2}];
            c = [outdat{:,3}];
        catch
        end
    end
end

function ViewCodes(qaplot, mask, vals, n)
    cdata   = get(qaplot, 'CData');
    ctldata = cdata(1:n,1);
    ctldata(mask) = vals{3};
    ctldata = [ctldata ctldata];
    flgdata = cdata(n+1:2*n,1);
    flgdata(mask) = vals{2};
    flgdata = [flgdata flgdata];
    valdata = cdata(2*n+1:end,1);
    valdata(mask) = vals{1};
    valdata = [valdata valdata];
    cdata   = [ctldata; flgdata; valdata];
    set(qaplot, 'CData', cdata);
end

function where = where()
    global RVIDs
    where = ['WHERE RawValueID IN (' num2str(RVIDs(1:end-1)','%d,') num2str(RVIDs(end)) ')'];
end

% --- Creates and returns a handle to the GUI figure.
function h1 = QAQC_GUI_dev_LayoutFcn(policy)
% policy - create a new figure or use a singleton. 'new' or 'reuse'.
    global uniqueCodes
    persistent hsingleton;
    if strcmpi(policy, 'reuse') & ishandle(hsingleton)
        h1 = hsingleton;
        return;
    end
    
    appdata = [];
    appdata.GUIDEOptions = struct(...
        'active_h', [], ...
        'taginfo', struct(...
        'figure', 2, ...
        'text', 44, ...
        'uitable', 2, ...
        'uipanel', 56, ...
        'listbox', 3, ...
        'radiobutton', 55, ...
        'popupmenu', 16), ...
        'override', 0, ...
        'release', 13, ...
        'resize', 'proportional', ...
        'accessibility', 'callback', ...
        'mfile', 1, ...
        'callbacks', 1, ...
        'singleton', 1, ...
        'syscolorfig', 1, ...
        'blocking', 0, ...
        'lastSavedFile', 'C:\Data\My Documents\JobRelated\MWDMS\MWDataMgmt\RT\Dev\QAQC_GUI_dev.m', ...
        'lastFilename', 'C:\Data\My Documents\JobRelated\MWDMS\MWDataMgmt\RT\Dev\QAQC_GUI_dev.fig');
    appdata.lastValidTag = 'figure1';
    appdata.GUIOnScreen = 1;
    appdata.GUIDELayoutEditor = [];
    appdata.initTags = struct(...
        'handle', [], ...
        'tag', 'figure1');

    valueMatrix = [0 1 2 3 4 8 -9 NaN];
    valueCell   = num2cell(valueMatrix);
    valueStruct = cell2struct(valueCell(:), {'None', 'Bad', 'Suspect', 'Unknown', 'Good', 'Replaced', 'Missing', 'Multi_or_NS'}); 
    valueValues = {};
    for fld = fieldnames(valueStruct)'
        valueValues{end+1} = [int2str(valueStruct.(fld{:})) ' ' fld{:}];
    end
    
    flagMatrix = [1 3 4 6 7 10 11 14 NaN];
    flagCell   = num2cell(flagMatrix);
    flagStruct = cell2struct(flagCell(:), {'Valid', 'Invalid', 'Suspect', 'Unknown', 'Null', 'Faulty', 'Out_of_Range', 'Climatology', 'Multi_or_NS'});
    flagValues = {};
    for fld = fieldnames(flagStruct)'
        flagValues{end+1} = [int2str(flagStruct.(fld{:})) ' ' fld{:}];
    end

    clMatrix = [0 1 2 3 4 5 NaN];
    clCell   = num2cell(clMatrix);
    clStruct = cell2struct(clCell(:), {'None', 'Processed', 'Reviewed', 'Post_processed', 'Final_EE_unavail', 'Final_EE_avail', 'Multi_or_NS'});
    clValues    = {};
    for fld = fieldnames(clStruct)'
        clValues{end+1} = [int2str(clStruct.(fld{:})) ' ' fld{:}];
    end

    h1 = figure(...
    'Units','normalized',...
    'Color',[0.925490196078431 0.913725490196078 0.847058823529412],...
    'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],...
    'IntegerHandle','off',...
    'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
    'MenuBar','none',...
    'Name','QAQC_GUI',...
    'NumberTitle','off',...
    'PaperPosition',get(0,'defaultfigurePaperPosition'),...
    'Position',[0.6 0.4 0.4 0.6],...
    'Resize','on',...
    'HandleVisibility','callback',...
    'Tag','figure1',...
    'UserData', {clMatrix, flagMatrix, valueMatrix},...
    'Visible','on');

    local_CreateFcn(h1, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel56';

    h2 = uipanel(...
    'Parent',h1,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel56',...
    'Clipping','on',...
    'Position',[0 0 1 1]);

    local_CreateFcn(h2, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel57';

    h3 = uipanel(...
    'Parent',h2,...
    'Units','normalized',...
    'Title',blanks(0),...    
    'Tag','uipanel57',...
    'Clipping','on',...
    'Position',[0 0.83 1 0.16]);

    local_CreateFcn(h3, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel70';

    h4 = uipanel(...
    'Parent',h3,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel70',...
    'Clipping','on',...
    'Position',[0.4 0.01 0.6 0.97]);

    local_CreateFcn(h4, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text49';

    if isfield(uniqueCodes, 'P')
        h5 = uicontrol(...
        'Parent',h4,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Position',[0.01 0.66 0.48 0.27],...
        'String','Data Quality Value',...
        'Style','text',...
        'Tag','text49');

        local_CreateFcn(h5, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text50';

        h6 = uicontrol(...
        'Parent',h4,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0.32 0.48 0.29],...
        'String','Data Quality Flag',...
        'Style','text',...
        'Tag','text50');

        local_CreateFcn(h6, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text51';

        h7 = uicontrol(...
        'Parent',h4,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0 0.48 0.27],...
        'String','Data Quality Control Value',...
        'Style','text',...
        'Tag','text51');

        local_CreateFcn(h7, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'PressDQV';

        Val = uniqueCodes.P.vl;
        if isempty(Val) ||  ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(valueValues);
        else
            val = find(valueMatrix==Val{:});
        end
        h8 = uicontrol(...
        'Parent',h4,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.65 0.48 0.30],...
        'String', {valueValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','PressDQV');
        if isempty(Val);
            set([h5 h8], 'Visible', 'off')
        end

        local_CreateFcn(h8, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'PressDQF';

        Val = uniqueCodes.P.fl;
        if isempty(Val) ||  ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(flagValues);
        else
            val = find(flagMatrix==Val{:});
        end
        h9 = uicontrol(...
        'Parent',h4,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.33 0.48 0.30],...
        'String', {flagValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','PressDQF');
        if isempty(Val)
            set([h6 h9], 'Visible', 'off')
        end

        local_CreateFcn(h9, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'PressDQC';

        Val = uniqueCodes.P.cl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(clValues);
        else
            val = find(clMatrix==Val{:});
        end
        h10 = uicontrol(...
        'Parent',h4,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0 0.48 0.30],...
        'String', {clValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','PressDQC');
        if isempty(Val)
            set([h7 h10], 'Visible', 'off')
        end

        local_CreateFcn(h10, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'uipanel71';

        h12 = uicontrol(...
        'Parent',h3,...
        'Units','normalized',...
        'FontSize',15,...
        'HorizontalAlignment','left',...
        'Position',[0.1 0.2 0.28 0.5],...
        'String','Pressure',...
        'Style','text',...
        'Tag','text48');
        P_off = strcmp(get(h5, 'Visible'), 'off') && ...
                strcmp(get(h6, 'Visible'), 'off') && ...
                strcmp(get(h7, 'Visible'), 'off');
        if P_off
            set(h12, 'Enable', 'off');
        end
        local_CreateFcn(h12, [], '', appdata);
    end
    
    appdata = [];
    appdata.lastValidTag = 'uipanel58';

    h13 = uipanel(...
    'Parent',h2,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel58',...
    'Clipping','on',...
    'Position',[0 0.665 1 0.16]);

    local_CreateFcn(h13, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel68';

    h14 = uipanel(...
    'Parent',h13,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel68',...
    'Clipping','on',...
    'Position',[0.4 0.01 0.6 0.97]);

    local_CreateFcn(h14, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text52';

    if isfield(uniqueCodes, 'T')
        h15 = uicontrol(...
        'Parent',h14,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Position',[0.01 0.66 0.48 0.27],...
        'String','Data Quality Value',...
        'Style','text',...
        'Tag','text52');

        local_CreateFcn(h15, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text53';

        h16 = uicontrol(...
        'Parent',h14,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0.32 0.48 0.29],...
        'String','Data Quality Flag',...
        'Style','text',...
        'Tag','text53');

        local_CreateFcn(h16, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text54';

        h17 = uicontrol(...
        'Parent',h14,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0 0.48 0.27],...
        'String','Data Quality Control Value',...
        'Style','text',...
        'Tag','text54');

        local_CreateFcn(h17, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'TempDQV';

        Val = uniqueCodes.T.vl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(valueValues);
        else
            val = find(valueMatrix==Val{:});
        end
        h18 = uicontrol(...
        'Parent',h14,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.65 0.48 0.30],...
        'String', {valueValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','TempDQV');
        if isempty(Val)
            set([h15 h18], 'Visible', 'off')
        end

        local_CreateFcn(h18, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'TempDQF';

        Val = uniqueCodes.T.fl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(flagValues);
        else
            val = find(flagMatrix==Val{:});
        end
        h19 = uicontrol(...
        'Parent',h14,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.33 0.48 0.30],...
        'String', {flagValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','TempDQF');
        if isempty(Val)
            set([h16 h19], 'Visible', 'off')
        end

        local_CreateFcn(h19, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'TempDQC';

        Val = uniqueCodes.T.cl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(clValues);
        else
            val = find(clMatrix==Val{:});
        end
        h20 = uicontrol(...
        'Parent',h14,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0 0.48 0.30],...
        'String', {clValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','TempDQC');
        if isempty(Val)
            set([h17 h20], 'Visible', 'off')
        end

        local_CreateFcn(h20, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text47';

        h21 = uicontrol(...
        'Parent',h13,...
        'Units','normalized',...
        'FontSize',15,...
        'HorizontalAlignment','left',...
        'Position',[0.1 0.2 0.28 0.5],...
        'String','Temperature',...
        'Style','text',...
        'Tag','text47');
        T_off = strcmp(get(h15, 'Visible'), 'off') && ...
                strcmp(get(h16, 'Visible'), 'off') && ...
                strcmp(get(h17, 'Visible'), 'off');
        if T_off
            set(h21, 'Enable', 'off');
        end
        local_CreateFcn(h21, [], '', appdata);
    end
    
    appdata = [];
    appdata.lastValidTag = 'uipanel59';

    h23 = uipanel(...
    'Parent',h2,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel59',...
    'Clipping','on',...
    'Position',[0 0.5 1 0.16]);

    local_CreateFcn(h23, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel66';

    h24 = uipanel(...
    'Parent',h23,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel66',...
    'Clipping','on',...
    'Position',[0.4 0.01 0.6 0.97]);

    local_CreateFcn(h24, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text55';

    if isfield(uniqueCodes, 'S')
        h25 = uicontrol(...
        'Parent',h24,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Position',[0.01 0.66 0.48 0.27],...
        'String','Data Quality Value',...
        'Style','text',...
        'Tag','text55');

        local_CreateFcn(h25, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text56';

        h26 = uicontrol(...
        'Parent',h24,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0.32 0.48 0.29],...
        'String','Data Quality Flag',...
        'Style','text',...
        'Tag','text56');

        local_CreateFcn(h26, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text57';

        h27 = uicontrol(...
        'Parent',h24,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0 0.48 0.27],...
        'String','Data Quality Control Value',...
        'Style','text',...
        'Tag','text57');

        local_CreateFcn(h27, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'SalDQV';

        Val = uniqueCodes.S.vl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(valueValues);
        else
            val = find(valueMatrix==Val{:});
        end
        h28 = uicontrol(...
        'Parent',h24,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.65 0.48 0.30],...
        'String', {valueValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','SalDQV');
        if isempty(Val)
            set([h25 h28], 'Visible', 'off')
        end

        local_CreateFcn(h28, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'SalDQF';

        Val = uniqueCodes.S.fl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(flagValues);
        else
            val = find(flagMatrix==Val{:});
        end
        h29 = uicontrol(...
        'Parent',h24,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.33 0.48 0.30],...
        'String', {flagValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','SalDQF');
        if isempty(Val)
            set([h26 h29], 'Visible', 'off')
        end

        local_CreateFcn(h29, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'SalDQC';

        Val = uniqueCodes.S.cl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(clValues);
        else
            val = find(clMatrix==Val{:});
        end
        h30 = uicontrol(...
        'Parent',h24,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0 0.48 0.30],...
        'String', {clValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','SalDQC');
        if isempty(Val)
            set([h27 h30], 'Visible', 'off')
        end

        local_CreateFcn(h30, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text46';

        h31 = uicontrol(...
        'Parent',h23,...
        'Units','normalized',...
        'FontSize',15,...
        'HorizontalAlignment','left',...
        'Position',[0.1 0.2 0.28 0.5],...
        'String','Salinity',...
        'Style','text',...
        'Tag','text46');
        S_off = strcmp(get(h25, 'Visible'), 'off') && ...
                strcmp(get(h26, 'Visible'), 'off') && ...
                strcmp(get(h27, 'Visible'), 'off');
        if S_off
            set(h31, 'Enable', 'off');
        end
        local_CreateFcn(h31, [], '', appdata);
    end
    
    appdata = [];
    appdata.lastValidTag = 'uipanel67';

    h33 = uipanel(...
    'Parent',h2,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel60',...
    'Clipping','on',...
    'Position',[0 0.33 1 0.16]);

    local_CreateFcn(h33, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel64';

    h34 = uipanel(...
    'Parent',h33,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel64',...
    'Clipping','on',...
    'Position',[0.4 0.01 0.6 0.97]);

    local_CreateFcn(h34, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text58';

    if isfield(uniqueCodes, 'O')
        h35 = uicontrol(...
        'Parent',h34,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Position',[0.01 0.66 0.48 0.27],...
        'String','Data Quality Value',...
        'Style','text',...
        'Tag','text58');

        local_CreateFcn(h35, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text59';

        h36 = uicontrol(...
        'Parent',h34,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0.32 0.48 0.29],...
        'String','Data Quality Flag',...
        'Style','text',...
        'Tag','text59');

        local_CreateFcn(h36, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text60';

        h37 = uicontrol(...
        'Parent',h34,...
        'Units','normalized',...
        'HorizontalAlignment','left',...
        'Min',1,...
        'Position',[0.01 0 0.48 0.27],...
        'String','Data Quality Control Value',...
        'Style','text',...
        'Tag','text60');

        local_CreateFcn(h37, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'DODQV';

        Val = uniqueCodes.O.vl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(valueValues);
        else
            val = find(valueMatrix==Val{:});
        end
        h38 = uicontrol(...
        'Parent',h34,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.65 0.48 0.30],...
        'String', {valueValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','DODQV');
        if isempty(Val)
            set([h35 h38], 'Visible', 'off')
        end

        local_CreateFcn(h38, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'DODQF';

        Val = uniqueCodes.O.fl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(flagValues);
        else
            val = find(flagMatrix==Val{:});
        end
        h39 = uicontrol(...
        'Parent',h34,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0.33 0.48 0.30],...
        'String', {flagValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','DODQF');
        if isempty(Val)
            set([h36 h39], 'Visible', 'off')
        end

        local_CreateFcn(h39, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'DODQC';

        Val = uniqueCodes.O.cl;
        if isempty(Val) || ...
           length(Val{:})>1 || ...
           all(isnan([Val{:}]))
            val = length(clValues);
        else
            val = find(clMatrix==Val{:});
        end
        h40 = uicontrol(...
        'Parent',h34,...
        'Units','normalized',...
        'BackgroundColor',[1 1 1],...
        'Position',[0.51 0 0.48 0.30],...
        'String', {clValues{1:end-1}, ''},...
        'Style','popupmenu',...
        'Value',val,...
        'Tag','DODQC');
        if isempty(Val)
            set([h37 h40], 'Visible', 'off')
        end

        local_CreateFcn(h40, [], '', appdata);

        appdata = [];
        appdata.lastValidTag = 'text45';

        h41 = uicontrol(...
        'Parent',h33,...
        'Units','normalized',...
        'FontSize',15,...
        'HorizontalAlignment','left',...
        'Position',[0.1 0.2 0.28 0.5],...
        'String','DO',...
        'Style','text',...
        'Tag','text45');
        DO_off = strcmp(get(h35, 'Visible'), 'off') && ...
                 strcmp(get(h36, 'Visible'), 'off') && ...
                 strcmp(get(h37, 'Visible'), 'off');
        if DO_off
            set(h41, 'Enable', 'off');
        end
        local_CreateFcn(h41, [], '', appdata);
    end

    appdata = [];
    appdata.lastValidTag = 'uipanel65';

    h43 = uipanel(...
    'Parent',h2,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel61',...
    'Clipping','on',...
    'Position',[0 0.16 1 0.16]);

    local_CreateFcn(h43, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel62';

    h44 = uipanel(...
    'Parent',h43,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel62',...
    'Clipping','on',...
    'Position',[0.4 0.01 0.6 0.97]);

    local_CreateFcn(h44, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text44';

    h45 = uicontrol(...
    'Parent',h43,...
    'Units','normalized',...
    'FontSize',15,...
    'HorizontalAlignment','left',...
    'Position',[0.1 0.2 0.28 0.5],...
    'String','Sampling Interval',...
    'Style','text',...
    'Tag','text44',...
    'Enable','off');

    local_CreateFcn(h45, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'uipanel63';

    h46 = uipanel(...
    'Parent',h43,...
    'Units','normalized',...
    'Title',blanks(0),...
    'Tag','uipanel63',...
    'Clipping','on',...
    'Position',[0.4 0.01 0.6 0.97]);

    local_CreateFcn(h46, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text61';

    h47 = uicontrol(...
    'Parent',h46,...
    'Units','normalized',...
    'HorizontalAlignment','left',...
    'Position',[0.01 0.66 0.48 0.27],...
    'String','Data Quality Value',...
    'Style','text',...
    'Tag','text61');

    local_CreateFcn(h47, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text62';

    h48 = uicontrol(...
    'Parent',h46,...
    'Units','normalized',...
    'HorizontalAlignment','left',...
    'Min',1,...
    'Position',[0.01 0.32 0.48 0.29],...
    'String','Data Quality Flag',...
    'Style','text',...
    'Tag','text62');

    local_CreateFcn(h48, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'text63';

    h49 = uicontrol(...
    'Parent',h46,...
    'Units','normalized',...
    'HorizontalAlignment','left',...
    'Min',1,...
    'Position',[0.01 0 0.48 0.27],...
    'String','Data Quality Control Value',...
    'Style','text',...
    'Tag','text63');

    local_CreateFcn(h49, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'SampIntDQV';

    h50 = uicontrol(...
    'Enable','off',...    
    'Parent',h46,...
    'Units','normalized',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.51 0.65 0.48 0.30],...
    'String', {valueValues{1:end-1}, ''},...
    'Style','popupmenu',...
    'Value',1,...
    'Tag','SampIntDQV'); %,...

    local_CreateFcn(h50, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'SampIntDQF';

    h51 = uicontrol(...
    'Enable','off',...    
    'Parent',h46,...
    'Units','normalized',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.51 0.33 0.48 0.30],...
    'String', {flagValues{1:end-1}, ''},...
    'Style','popupmenu',...
    'Value',1,...
    'Tag','SampIntDQF');

    local_CreateFcn(h51, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'SampIntDQC';

    h52 = uicontrol(...
    'Enable','off',...    
    'Parent',h46,...
    'Units','normalized',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.51 0 0.48 0.30],...
    'String', {clValues{1:end-1}, ''},...
    'Style','popupmenu',...
    'Value',1,...
    'Tag','SampIntDQC');

    local_CreateFcn(h52, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'pushbutton1';

    h53 = uicontrol(...
    'Parent',h2,...
    'Units','normalized',...
    'FontSize',12,...
    'Position',[0.05 0.05 0.2 0.05],...
    'String','Push & View',...
    'Tag','preview_button',...
    'Callback',@(hObject,eventdata)QAQC_GUI_dev('ActionsCallback',hObject,eventdata,guidata(hObject),h1));

    local_CreateFcn(h53, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'pushbutton2';

    h54 = uicontrol(...
    'Parent',h2,...
    'Units','normalized',...
    'FontSize',12,...
    'Position',[0.4 0.05 0.2 0.05],...
    'String','Undo',...
    'Tag','undo_button',...
    'Callback',@(hObject,eventdata)QAQC_GUI_dev('ActionsCallback',hObject,eventdata,guidata(hObject),'Undo')...
    );

    local_CreateFcn(h54, [], '', appdata);

    appdata = [];
    appdata.lastValidTag = 'pushbutton2';

    h55 = uicontrol(...
    'Parent',h2,...
    'Units','normalized',...
    'FontSize',12,...
    'Position',[0.75 0.05 0.2 0.05],...
    'String','Commit',...
    'Tag','commit_button',...
    'Callback',@(hObject,eventdata)QAQC_GUI_dev('ActionsCallback',hObject,eventdata,guidata(hObject),'Commit')...
    );

    local_CreateFcn(h55, [], '', appdata);
    hsingleton = h1;
end

% --- Set application data first then calling the CreateFcn. 
function local_CreateFcn(hObject, eventdata, createfcn, appdata)
    if ~isempty(appdata)
       names = fieldnames(appdata);
       for i=1:length(names)
           name = char(names(i));
           setappdata(hObject, name, getfield(appdata,name));
       end
    end
end

% --- Handles default GUIDE GUI creation and callback dispatch
function varargout = gui_mainfcn(gui_State, varargin)
    gui_StateFields =  {'gui_Name'
        'gui_Singleton'
        'gui_OpeningFcn'
        'gui_OutputFcn'
        'gui_LayoutFcn'
        'gui_Callback'};
    gui_Mfile = '';
    for i=1:length(gui_StateFields)
        if ~isfield(gui_State, gui_StateFields{i})
            error('MATLAB:gui_mainfcn:FieldNotFound', 'Could not find field %s in the gui_State struct in GUI M-file %s', gui_StateFields{i}, gui_Mfile);
        elseif isequal(gui_StateFields{i}, 'gui_Name')
            gui_Mfile = [gui_State.(gui_StateFields{i}), '.m'];
        end
    end

    numargin = length(varargin);

    if numargin == 0
        % QAQC_GUI_DEV
        % create the GUI only if we are not in the process of loading it
        % already
        gui_Create = true;
    elseif local_isInvokeActiveXCallback(gui_State, varargin{:})
        % QAQC_GUI_DEV(ACTIVEX,...)
        vin{1} = gui_State.gui_Name;
        vin{2} = [get(varargin{1}.Peer, 'Tag'), '_', varargin{end}];
        vin{3} = varargin{1};
        vin{4} = varargin{end-1};
        vin{5} = guidata(varargin{1}.Peer);
        feval(vin{:});
        return;
    elseif local_isInvokeHGCallback(gui_State, varargin{:})
        % QAQC_GUI_DEV('CALLBACK',hObject,eventData,handles,...)
        gui_Create = false;
    else
        % QAQC_GUI_DEV(...)
        % create the GUI and hand varargin to the openingfcn
        gui_Create = true;
    end

    if ~gui_Create
        % In design time, we need to mark all components possibly created in
        % the coming callback evaluation as non-serializable. This way, they
        % will not be brought into GUIDE and not be saved in the figure file
        % when running/saving the GUI from GUIDE.
        designEval = false;
        if (numargin>1 && ishghandle(varargin{2}))
            fig = varargin{2};
            while ~isempty(fig) && ~isa(handle(fig),'figure')
                fig = get(fig,'parent');
            end

            designEval = isappdata(0,'CreatingGUIDEFigure') || isprop(fig,'__GUIDEFigure');
        end

        if designEval
            beforeChildren = findall(fig);
        end

        % evaluate the callback now
        varargin{1} = gui_State.gui_Callback;
        if nargout
            [varargout{1:nargout}] = feval(varargin{:});
        else       
            feval(varargin{:});
        end

        % Set serializable of objects created in the above callback to off in
        % design time. Need to check whether figure handle is still valid in
        % case the figure is deleted during the callback dispatching.
        if designEval && ishandle(fig)
            set(setdiff(findall(fig),beforeChildren), 'Serializable','off');
        end
    else
        if gui_State.gui_Singleton
            gui_SingletonOpt = 'reuse';
        else
            gui_SingletonOpt = 'new';
        end

        % Check user passing 'visible' P/V pair first so that its value can be
        % used by oepnfig to prevent flickering
        gui_Visible = 'auto';
        gui_VisibleInput = '';
        for index=1:2:length(varargin)
            if length(varargin) == index || ~ischar(varargin{index})
                break;
            end

            % Recognize 'visible' P/V pair
            len1 = min(length('visible'),length(varargin{index}));
            len2 = min(length('off'),length(varargin{index+1}));
            if ischar(varargin{index+1}) && strncmpi(varargin{index},'visible',len1) && len2 > 1
                if strncmpi(varargin{index+1},'off',len2)
                    gui_Visible = 'invisible';
                    gui_VisibleInput = 'off';
                elseif strncmpi(varargin{index+1},'on',len2)
                    gui_Visible = 'visible';
                    gui_VisibleInput = 'on';
                end
            end
        end

        % Open fig file with stored settings.  Note: This executes all component
        % specific CreateFunctions with an empty HANDLES structure.


        % Do feval on layout code in m-file if it exists
        gui_Exported = ~isempty(gui_State.gui_LayoutFcn);
        % this application data is used to indicate the running mode of a GUIDE
        % GUI to distinguish it from the design mode of the GUI in GUIDE. it is
        % only used by actxproxy at this time.   
        setappdata(0,genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]),1);
        if gui_Exported
            gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);

            % make figure invisible here so that the visibility of figure is
            % consistent in OpeningFcn in the exported GUI case
            if isempty(gui_VisibleInput)
                gui_VisibleInput = get(gui_hFigure,'Visible');
            end
            set(gui_hFigure,'Visible','off')

            % openfig (called by local_openfig below) does this for guis without
            % the LayoutFcn. Be sure to do it here so guis show up on screen.
            movegui(gui_hFigure,'onscreen');
        else
            gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt, gui_Visible);
            % If the figure has InGUIInitialization it was not completely created
            % on the last pass.  Delete this handle and try again.
            if isappdata(gui_hFigure, 'InGUIInitialization')
                delete(gui_hFigure);
                gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt, gui_Visible);
            end
        end
        if isappdata(0, genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]))
            rmappdata(0,genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]));
        end

        % Set flag to indicate starting GUI initialization
        setappdata(gui_hFigure,'InGUIInitialization',1);

        % Fetch GUIDE Application options
        gui_Options = getappdata(gui_hFigure,'GUIDEOptions');
        % Singleton setting in the GUI M-file takes priority if different
        gui_Options.singleton = gui_State.gui_Singleton;

        if ~isappdata(gui_hFigure,'GUIOnScreen')
            % Adjust background color
            if gui_Options.syscolorfig
                set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));
            end

            % Generate HANDLES structure and store with GUIDATA. If there is
            % user set GUI data already, keep that also.
            data = guidata(gui_hFigure);
            handles = guihandles(gui_hFigure);
            if ~isempty(handles)
                if isempty(data)
                    data = handles;
                else
                    names = fieldnames(handles);
                    for k=1:length(names)
                        data.(char(names(k)))=handles.(char(names(k)));
                    end
                end
            end
            guidata(gui_hFigure, data);
        end

        % Apply input P/V pairs other than 'visible'
        for index=1:2:length(varargin)
            if length(varargin) == index || ~ischar(varargin{index})
                break;
            end

            len1 = min(length('visible'),length(varargin{index}));
            if ~strncmpi(varargin{index},'visible',len1)
                try set(gui_hFigure, varargin{index}, varargin{index+1}), catch break, end
            end
        end

        % If handle visibility is set to 'callback', turn it on until finished
        % with OpeningFcn
        gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
        if strcmp(gui_HandleVisibility, 'callback')
            set(gui_hFigure,'HandleVisibility', 'on');
        end

        feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});

        if isscalar(gui_hFigure) && ishandle(gui_hFigure)
            % Handle the default callbacks of predefined toolbar tools in this
            % GUI, if any
            guidemfile('restoreToolbarToolPredefinedCallback',gui_hFigure); 

            % Update handle visibility
            set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);

            % Call openfig again to pick up the saved visibility or apply the
            % one passed in from the P/V pairs
            if ~gui_Exported
                gui_hFigure = local_openfig(gui_State.gui_Name, 'reuse',gui_Visible);
            elseif ~isempty(gui_VisibleInput)
                set(gui_hFigure,'Visible',gui_VisibleInput);
            end
            if strcmpi(get(gui_hFigure, 'Visible'), 'on')
                figure(gui_hFigure);

                if gui_Options.singleton
                    setappdata(gui_hFigure,'GUIOnScreen', 1);
                end
            end

            % Done with GUI initialization
            if isappdata(gui_hFigure,'InGUIInitialization')
                rmappdata(gui_hFigure,'InGUIInitialization');
            end

            % If handle visibility is set to 'callback', turn it on until
            % finished with OutputFcn
            gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
            if strcmp(gui_HandleVisibility, 'callback')
                set(gui_hFigure,'HandleVisibility', 'on');
            end
            gui_Handles = guidata(gui_hFigure);
        else
            gui_Handles = [];
        end

        if nargout
            [varargout{1:nargout}] = feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
        else
            feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
        end

        if isscalar(gui_hFigure) && ishandle(gui_hFigure)
            set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);
        end
    end
end

function gui_hFigure = local_openfig(name, singleton, visible)
% openfig with three arguments was new from R13. Try to call that first, if
% failed, try the old openfig.
    if nargin('openfig') == 2
        % OPENFIG did not accept 3rd input argument until R13,
        % toggle default figure visible to prevent the figure
        % from showing up too soon.
        gui_OldDefaultVisible = get(0,'defaultFigureVisible');
        set(0,'defaultFigureVisible','off');
        gui_hFigure = openfig(name, singleton);
        set(0,'defaultFigureVisible',gui_OldDefaultVisible);
    else
        gui_hFigure = openfig(name, singleton, visible);
    end
end

function result = local_isInvokeActiveXCallback(gui_State, varargin)
    try
        result = ispc && iscom(varargin{1}) ...
                 && isequal(varargin{1},gcbo);
    catch
        result = false;
    end
end

function result = local_isInvokeHGCallback(gui_State, varargin)
    try
        fhandle = functions(gui_State.gui_Callback);
        result = ~isempty(findstr(gui_State.gui_Name,fhandle.file)) || ...
                 (ischar(varargin{1}) ...
                 && isequal(ishandle(varargin{2}), 1) ...
                 && (~isempty(strfind(varargin{1},[get(varargin{2}, 'Tag'), '_'])) || ...
                    ~isempty(strfind(varargin{1}, '_CreateFcn'))) );
    catch
        result = false;
    end
end